package com.fcy.teamwork.jmservice.event

import cn.jpush.im.android.api.event.MessageEvent
import cn.jpush.im.android.api.model.GroupInfo
import cn.jpush.im.android.api.model.Message
import cn.jpush.im.android.api.model.UserInfo
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow

class UnReadEventListener:BaseEventListener() {
    val unReadFlow = MutableSharedFlow<String>(
        replay = 0,
        extraBufferCapacity = 1,
        onBufferOverflow = BufferOverflow.SUSPEND
    )

    fun onEvent(event: MessageEvent) {
        val identify = event.message.getIdentify()
        unReadFlow.tryEmit(identify)
    }
}

fun Message.getIdentify(): String =
    when (val info = targetInfo) {
        is UserInfo -> {
            info.userName
        }
        is GroupInfo -> {
            info.groupID.toString()
        }
        else -> throw IllegalArgumentException("出现未知类型")
    }
